#include <condition_variable>
#include <chrono>
#include <fstream>
#include <unistd.h>
#include <sstream>
#include <iomanip>
#include <thread>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/ioctl.h>
#include <net/if.h>

#include "sysIf.h"
#include "ConfigManager.h"
#include "ProtocolApi.h"
#include "ConfigApi.h"

using namespace Protocol;
using namespace ConfigApi;


ConfigManager::Ptr ConfigManager::Instance(){
    static auto ptr = std::make_shared<ConfigManager>();
    return ptr;
}

ConfigManager::ConfigManager(){
    RegistRPC();
}

ConfigManager::~ConfigManager(){

}

void ConfigManager::RegistRPC(){
    IProtocolInterface::GetInstance()->AuditoryworksRegistRequestRpc("getDeviceConfig", 
        [this](const Json::Value& req_params, Json::Value& res_result, std::string& errinfo){
            return getDeviceConfig(req_params, res_result, errinfo);
        });
    IProtocolInterface::GetInstance()->AuditoryworksRegistRequestRpc("setDeviceConfig", 
        [this](const Json::Value& req_params, Json::Value& res_result, std::string& errinfo){
            return setDeviceConfig(req_params, res_result, errinfo);
        });
}


bool ConfigManager::getDeviceConfig(const Json::Value& req_params, Json::Value& res_result, std::string& errinfo){
    if(!req_params.isMember("Name") || !req_params["Name"].isString()){
        return false;
    }

    std::string subConfig =  req_params["Name"].asString();
    Json::Value Config;
    if(!IConfigInterface::GetInstance()->Get(subConfig.c_str(), Config)){
        return false;
    }
    res_result[subConfig] = Config;
    return true;
}

bool ConfigManager::setDeviceConfig(const Json::Value& req_params, Json::Value& res_result, std::string& errinfo){
    if(!req_params.isMember("Name") || !req_params["Name"].isString()){
        return false;
    }
    if(!req_params.isMember("Option") || !req_params["Option"].isInt()){
        return false;
    }
    if(!req_params.isMember("Config")){
        return false;
    }
    if(!IConfigInterface::GetInstance()->Set(req_params["Name"].asCString(), req_params["Config"], req_params["Option"].asInt())){
        return false;
    }
    return true;
}
